package com.wlr.blog.web.common.utils;

import com.alibaba.druid.util.StringUtils;
import com.wlr.blog.util.common.exception.CustomException;
import com.wlr.blog.web.common.entity.User;
import io.jsonwebtoken.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lrwang
 * @version 1.0
 * @date 2023/1/16 14:53
 */
public class CreateJwt {
    public static String getToken(User user) {
        JwtBuilder builder = Jwts.builder();
        String token = builder
                .setId(user.getUserName())
                .setSubject(user.getUserName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 1000 * 30))
                .signWith(SignatureAlgorithm.HS256, "991009")
                .compact();
        return token;
    }

    public static void analysisToken(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new CustomException("请先进行登陆");
        } else {
            JwtParser parser = Jwts.parser();
            parser.setSigningKey("991009");
            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            String subject = body.getSubject();
            System.out.println("用户id:" + body.getId());
            System.out.println("用户名:" + body.getSubject());
            System.out.println("用户时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
                    format(body.getIssuedAt()));
            System.out.println("过期时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
                    format(body.getExpiration()));
            System.out.println("用户角色:" + body.get("role"));
        }
    }
}
